<template>
	<div>
		<van-row type="flex" justify="center">
			<van-image :src="require('@/assets/images/logo.png')"></van-image>
		</van-row>
		<van-cell-group inset>
			<!-- 输入账号(用户名) -->
			<van-field label="账号" placeholder="请输入账号" v-model="loginForm.name"></van-field>
			<!-- 输入密码 -->
			<van-field label="密码" placeholder="请输入密码" type="password" v-model="loginForm.password"></van-field>
			<!-- 登录按钮 -->
			<van-button type="primary" size="large" @click="onClickLogin">登录</van-button>
			<!-- 注册按钮 -->
			<van-button class="goto" type="info" size="large" @click="onClickRegister">如果没有账号,清立即注册</van-button>
		</van-cell-group>
	</div>
</template>

<script>
	import {
		loginAPI
	} from "@/api/user.js"; //导入登录接口
	import * as Auth from "@/utils/auth.js"
	export default {
		name: "login",
		data() {
			return {
				loginForm: {
					name: "dingding", //用户名 设置默认值，仅是方便调试
					password: "123456",
				}
			}
		},
		mounted() {
			//初始赋值,从本地存储中获取用户名
			this.loginForm.name=Auth.getUserLocal().name;
		},
		methods:{
			onClickLogin(){
				// this.$toast("登录，还没实现")
				if(this.loginForm.name==="" || this.loginForm.password==="" ){
					this.$toast("账号或密码不能为空");
					return;
				}
				let params=this.loginForm;
				loginAPI(params).then(result=>{
					console.log(result);
					this.$toast({message:"登录成功!",duration:1000});
					//把返回的user、token在本地保存
					Auth.setTokenLocal(result.data.token);  //保存token
					Auth.setUserLocal(result.data.user);  //保存用户数据
					
					//实现路由跳转  哪个页面 当前路由如果有重定向跳转地址 user
					let toPath=this.$route.params.redirect || "user";
					this.$router.replace({path:toPath});
				})
			},
			onClickRegister(){
				//路由跳转到用户注册页面
				this.$router.push({name:"register"});
			}
		}
	}
</script>

<style lang="less" scoped="scoped">
	.goto{
		display: block;
		margin-top: 25px;
		text-align: center;
	}
</style>
